package model

import (
	"time"
	"user_srv/basic/config"
)

// 通知表
type XqNotifications struct {
	Id        int64     `gorm:"column:id;type:bigint;primaryKey;not null;" json:"id"`
	UserId    int64     `gorm:"column:user_id;type:bigint;comment:用户ID;not null;" json:"user_id"`             // 用户ID
	Type      int8      `gorm:"column:type;type:tinyint(1);comment:通知类型 1:匹配通知 2:消息通知;not null;" json:"type"` // 通知类型
	Title     string    `gorm:"column:title;type:varchar(100);comment:通知标题;not null;" json:"title"`           // 通知标题
	Content   string    `gorm:"column:content;type:text;comment:通知内容;not null;" json:"content"`               // 通知内容
	RelatedId int64     `gorm:"column:related_id;type:bigint;comment:关联ID（匹配ID或消息ID）;" json:"related_id"`     // 关联ID
	IsRead    int8      `gorm:"column:is_read;type:tinyint(1);comment:是否已读;default:0;" json:"is_read"`        // 是否已读
	CreatedAt time.Time `gorm:"column:created_at;type:timestamp;default:CURRENT_TIMESTAMP;" json:"created_at"`
}

func (x *XqNotifications) TableName() string {
	return "xq_notifications"
}

func (x *XqNotifications) Create() error {
	return config.DB.Create(&x).Error
}

func (x *XqNotifications) Delete(where XqNotifications) error {
	return config.DB.Where(where).Delete(&x).Error
}

func (x *XqNotifications) Update(where XqNotifications) error {
	return config.DB.Where(where).Updates(&x).Error
}

func (x *XqNotifications) List(where XqNotifications) ([]XqNotifications, error) {
	var notifications []XqNotifications
	err := config.DB.Where(where).Find(&notifications).Error
	return notifications, err
}

func (x *XqNotifications) GetById(id int64) (*XqNotifications, error) {
	var notification XqNotifications
	err := config.DB.Where("id = ?", id).First(&notification).Error
	return &notification, err
}

func (x *XqNotifications) ListByUserId(userId int64, limit, offset int) ([]XqNotifications, error) {
	var notifications []XqNotifications
	query := config.DB.Where("user_id = ?", userId)
	if limit > 0 {
		query = query.Limit(limit)
	}
	if offset > 0 {
		query = query.Offset(offset)
	}
	err := query.Order("created_at DESC").Find(&notifications).Error
	return notifications, err
}

func (x *XqNotifications) MarkAsRead(userId, notificationId int64) error {
	return config.DB.Model(&XqNotifications{}).
		Where("id = ? AND user_id = ?", notificationId, userId).
		Update("is_read", 1).Error
}

func (x *XqNotifications) MarkAllAsRead(userId int64) error {
	return config.DB.Model(&XqNotifications{}).
		Where("user_id = ? AND is_read = 0", userId).
		Update("is_read", 1).Error
}

func (x *XqNotifications) GetUnreadCount(userId int64) (int64, error) {
	var count int64
	err := config.DB.Model(&XqNotifications{}).
		Where("user_id = ? AND is_read = 0", userId).
		Count(&count).Error
	return count, err
}
